package com.neu.edu.interceptor;

import com.neu.common.constant.AuthServerConstant;
import com.neu.common.constant.CartConstant;
import com.neu.common.vo.MemberResponseVo;
import com.neu.edu.to.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     *  在目标方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null){
            // 用户已经登陆
            userInfoTo.setUserId(member.getId());
        }

        // 未登录查看是否有 user-key，从cookie中查询是否有  user-key
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    // 存在user-key
                    userInfoTo.setUserKey(cookie.getValue());
                    //标记为已是临时用户，就无需再次向cookie中保存数据了
                    userInfoTo.setTempUser(true);
                }
            }
        }

        // 如果是第一次登录(即未登录，也没有user-key)，则生成一个user-key
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String string = UUID.randomUUID().toString();
            userInfoTo.setUserKey(string);
        }

        // 保存
        threadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //如果浏览器没有没有临时用户信息，则一定保存一个临时用户
        if (!userInfoTo.getTempUser()){
            // 把临时用户信息存入到cookie中
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            //扩大作用域
            cookie.setDomain("gulimall.com");
            //设置过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
